<template>
  <div class="app-container">
    <el-row :gutter="20">
      <splitpanes :horizontal="this.$store.getters.device === 'mobile'" class="default-theme">
        <!--供应商-->
        <pane size="20">
          <el-col>
            <el-card class="supplier-card">
              <div slot="header" class="supplier-header">
                <span class="title">供应商列表</span>
                <el-input
                  v-model="supplierId"
                  placeholder="搜索供应商ID"
                  clearable
                  size="small"
                  prefix-icon="el-icon-search"
                  class="search-input"
                />
              </div>
              <el-tree
                :data="deptOptions"
                :props="defaultProps"
                :expand-on-click-node="false"
                :filter-node-method="filterNode"
                ref="tree"
                node-key="id"
                default-expand-all
                highlight-current
                @node-click="handleNodeClick"
                class="supplier-tree"
              />
            </el-card>
          </el-col>
        </pane>

        <!--购物车内容-->
        <pane size="80">
          <el-col>
            <el-card class="cart-card">
              <div class="cart-header">
                <div class="total-price">
                  <span class="label">总价:</span>
                  <span class="amount">¥{{ formatPrice(finalTotalAmount) }}</span>
                </div>
                <div class="action-buttons">
                  <el-button type="primary" icon="el-icon-shopping-cart-2" @click="placeOrder">勾选下订单</el-button>
                  <el-button type="info" icon="el-icon-refresh" @click="handleReset">重置</el-button>
                  <el-button type="success" icon="el-icon-document" @click="selectPersonOrders">查看个人订单</el-button>
                </div>
              </div>

              <el-table
                v-loading="loading"
                :data="purchcarList"
                @selection-change="handleSelectionChange"
                row-key="carId"
                ref="purchcarTable"
                class="cart-table"
                :header-cell-style="{background:'#f5f7fa'}"
                :row-class-name="tableRowClassName"
              >
                <el-table-column type="selection" width="55" align="center" :selectable="isSelectable"/>
                <el-table-column label="产品图片" align="center" width="120">
                  <template slot-scope="scope">
                    <el-image
                      :src="scope.row.imageUrl.split(',')[0]"
                      fit="cover"
                      style="width: 80px; height: 80px"
                      :preview-src-list="[scope.row.imageUrl.split(',')[0]]"
                    >
                      <div slot="error" class="image-slot">
                        <i class="el-icon-picture-outline"></i>
                      </div>
                    </el-image>
                  </template>
                </el-table-column>
                <el-table-column label="产品名称" prop="productName">
                  <template slot-scope="scope">
                    <div class="product-info" :class="{'out-of-stock': scope.row.stockQuantity <= 0}">
                      <div class="product-name">{{ scope.row.productName }}</div>
                      <div class="product-id">商品ID: {{ scope.row.productId }}</div>
                    </div>
                  </template>
                </el-table-column>
                <el-table-column label="单价" align="center" width="120">
                  <template slot-scope="scope">
                    <span class="price">¥{{ formatPrice(scope.row.unitPrice) }}</span>
                  </template>
                </el-table-column>
                <el-table-column label="数量" align="center" width="120">
                  <template slot-scope="scope">
                    <span class="quantity">{{ scope.row.quantity }}</span>
                  </template>
                </el-table-column>
                <el-table-column label="库存" align="center" width="100">
                  <template slot-scope="scope">
                    <span class="stock-quantity" :class="{'stock-warning': scope.row.stockQuantity < 10 && scope.row.stockQuantity > 0, 'stock-danger': scope.row.stockQuantity <= 0}">
                      {{ scope.row.stockQuantity }}
                    </span>
                  </template>
                </el-table-column>
                <el-table-column label="总金额" align="center" width="150">
                  <template slot-scope="scope">
                    <span class="total-amount">¥{{ formatPrice(scope.row.totalAmount) }}</span>
                  </template>
                </el-table-column>
                <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                  <template slot-scope="scope">
                    <el-button
                      size="mini"
                      type="text"
                      icon="el-icon-edit"
                      @click="handleUpdate(scope.row)"
                      v-hasPermi="['supply:purchcar:edit']"
                      :disabled="scope.row.stockQuantity <= 0"
                    >修改
                    </el-button>
                    <el-button
                      size="mini"
                      type="text"
                      icon="el-icon-delete"
                      @click="handleDelete(scope.row)"
                      v-hasPermi="['supply:purchcar:remove']"
                    >删除
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>

              <pagination
                v-show="total>0"
                :total="total"
                :page.sync="queryParams.pageNum"
                :limit.sync="queryParams.pageSize"
                @pagination="getList"
                class="pagination-container"
              />
            </el-card>
          </el-col>
        </pane>
      </splitpanes>

    </el-row>

    <!-- 添加或修改购物车对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="产品名称">
          <div class="product-name-display">{{ form.productName || '未知产品' }}</div>
        </el-form-item>
        <el-form-item label="当前库存">
          <div class="stock-display">
            <span :class="{'stock-danger': form.stockQuantity <= 0, 'stock-warning': form.stockQuantity > 0 && form.stockQuantity < 10, 'stock-normal': form.stockQuantity >= 10}">
              {{ form.stockQuantity || 0 }}
            </span>
            <span class="stock-unit">件</span>
            <el-tag
              size="mini"
              :type="form.stockQuantity <= 0 ? 'danger' : form.stockQuantity < 10 ? 'warning' : 'success'"
              class="stock-status"
            >
              {{ form.stockQuantity <= 0 ? '无库存' : form.stockQuantity < 10 ? '库存紧张' : '库存充足' }}
            </el-tag>
          </div>
        </el-form-item>
        <el-form-item label="产品数量" prop="quantity">
          <el-input-number
            v-model="form.quantity"
            :min="1"
            :max="form.stockQuantity || 0"
            :disabled="form.stockQuantity <= 0"
            placeholder="请输入产品数量"
          />
          <span class="quantity-tip" v-if="form.stockQuantity > 0">
            (最多可购买: {{ form.stockQuantity }}件)
          </span>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" :disabled="form.stockQuantity <= 0">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>


    <!-- 下订单对话框 -->
    <el-dialog
      title="订单确认"
      :visible.sync="orderVisible"
      width="500px"
      @close="handleOrderDialogClose"
      custom-class="order-dialog"
    >
      <div class="order-content">
        <div class="order-summary">
          <div class="summary-header">
            <span class="title">已选商品 ({{ selectedOrderItems.length }}件)</span>
          </div>
          <el-scrollbar class="order-list">
            <div v-for="(item, index) in selectedOrderItems" :key="index" class="order-item">
              <div class="item-left">
                <el-image
                  :src="item.imageUrl.split(',')[0]"
                  fit="cover"
                  class="product-img"
                  :preview-src-list="[item.imageUrl.split(',')[0]]"
                >
                  <div slot="error" class="image-slot">
                    <i class="el-icon-picture-outline"></i>
                  </div>
                </el-image>
                <div class="product-info">
                  <div class="product-name">{{ item.productName }}</div>
                  <div class="product-price">¥{{ formatPrice(item.orderAmount / item.quantity) }}</div>
                </div>
              </div>
              <div class="item-right">
                <div class="quantity">x{{ item.quantity }}</div>
                <div class="item-total">¥{{ formatPrice(item.orderAmount) }}</div>
              </div>
            </div>
          </el-scrollbar>
        </div>

        <!-- 添加地址选择部分 -->
        <div class="address-section">
          <div class="section-header">
            <span class="title">
              <i class="el-icon-location"></i>
              收货地址
            </span>
            <el-button type="text" @click="showAddAddressDialog">
              <i class="el-icon-plus"></i>
              新增地址
            </el-button>
          </div>
          <div class="address-list">
            <el-empty v-if="addressList.length === 0" description="暂无收货地址"></el-empty>
            <el-scrollbar v-else height="250px">
              <el-radio-group v-model="selectedAddressId" class="address-radio-group">
                <el-radio
                  v-for="addr in addressList"
                  :key="addr.id"
                  :label="addr.id"
                  class="address-radio-item"
                  :class="{'is-selected': selectedAddressId === addr.id}"
                >
                  <div class="address-info">
                    <div class="address-tag">
                      <el-tag
                        size="small"
                        :type="addr.userName === '默认地址' ? 'success' : 'primary'"
                      >
                        {{ addr.userName }}
                      </el-tag>
                    </div>
                    <div class="address-main">{{ addr.address }}</div>
                    <div class="address-time">
                      <i class="el-icon-time"></i>
                      {{ addr.createTime }}
                    </div>
                  </div>
                </el-radio>
              </el-radio-group>
            </el-scrollbar>
          </div>
        </div>

        <div class="order-footer">
          <div class="total-info">
            <div class="total-item">
              <span class="label">商品总数：</span>
              <span class="value">{{ selectedOrderItems.length }}件</span>
            </div>
            <div class="total-item highlight">
              <span class="label">商品总价：</span>
              <span class="value price">¥{{ formatPrice(finalTotalAmount) }}</span>
            </div>
          </div>
        </div>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button plain size="medium" @click="orderVisible = false">
            <i class="el-icon-close"></i>
            取消
          </el-button>
          <el-button
            type="warning"
            size="medium"
            icon="el-icon-document"
            plain
            @click="handleAbandonOrder"
          >
            仅下单
          </el-button>
<!--          <el-button-->
<!--            type="warning"-->
<!--            size="medium"-->
<!--            icon="el-icon-document"-->
<!--            plain-->
<!--            @click="handleAbandonOrder"-->
<!--            v-has-permi="['supply:psorders:create2']"-->
<!--          >-->
<!--            仅下单-->
<!--          </el-button>-->

          <!-- <el-button
            type="primary"
            size="medium"
            icon="el-icon-shopping-cart-2"
            @click="handleConfirmOrder"
          >
            下单并支付
          </el-button> -->
        </div>
      </template>
    </el-dialog>

    <!-- 支付对话框 -->
    <!-- 普通用户支付对话框 -->
    <el-dialog
      title="选择支付方式"
      :visible.sync="payDialogVisible"
      width="400px"
      @close="handlePayClose">
      <el-skeleton :loading="loading" animated>
        <template #template>
          <el-skeleton-item variant="text" style="width: 30%"/>
          <el-skeleton-item variant="text"/>
          <el-skeleton-item variant="text" style="width: 60%"/>
        </template>
        <template #default>
          <div class="goods-details">
            <h3>商品明细（共 {{ selectedOrderItems.length }} 项）</h3>
            <el-table :data="selectedOrderItems" border size="mini">
              <el-table-column prop="productName" label="商品名称" width="200"/>
              <el-table-column label="单价" width="120">
                <template #default="{row}">￥{{ (row.orderAmount / row.quantity).toFixed(2) }}</template>
              </el-table-column>
              <el-table-column prop="quantity" label="数量" width="100"/>
              <el-table-column label="小计" width="120">
                <template #default="{row}">
                  ￥{{ row.orderAmount.toFixed(2) }}
                </template>
              </el-table-column>
            </el-table>
            <div class="total-amount">
              订单总额：<span class="amount">￥{{ finalTotalAmount.toFixed(2) }}</span>
            </div>
          </div>
        </template>
      </el-skeleton>
      <div style="text-align:center;">
        <el-radio-group v-model="selectedPayMethod">
          <el-radio label="微信支付" border>
            <i class="el-icon-success" style="color:#67C23A;"></i>
            微信支付
          </el-radio>
          <el-radio label="支付宝支付" border>
            <i class="el-icon-success" style="color:#409EFF;"></i>
            支付宝支付
          </el-radio>
        </el-radio-group>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="payDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirmPay">立即支付</el-button>
      </div>
    </el-dialog>


    <!-- 战略合作商支付对话框 -->
    <el-dialog
      title="选择支付方式"
      :visible.sync="payDialogVisible1"
      width="400px"
      @close="handlePayClose">
      <el-skeleton :loading="loading" animated>
        <template #template>
          <el-skeleton-item variant="text" style="width: 30%"/>
          <el-skeleton-item variant="text"/>
          <el-skeleton-item variant="text" style="width: 60%"/>
        </template>
        <template #default>
          <div class="goods-details">
            <h3>商品明细（共 {{ selectedOrderItems.length }} 项）</h3>
            <el-table :data="selectedOrderItems" border size="mini">
              <el-table-column prop="productName" label="商品名称" width="200"/>
              <el-table-column label="单价" width="120">
                <template #default="{row}">￥{{ (row.orderAmount / row.quantity).toFixed(2) }}</template>
              </el-table-column>
              <el-table-column prop="quantity" label="数量" width="100"/>
              <el-table-column label="小计" width="120">
                <template #default="{row}">
                  ￥{{ row.orderAmount.toFixed(2) }}
                </template>
              </el-table-column>
            </el-table>
            <div class="total-amount">
              订单总额：<span class="amount">￥{{ finalTotalAmount.toFixed(2) }}</span>
            </div>
          </div>
        </template>
      </el-skeleton>
      <div style="text-align:center;">
        <el-radio-group v-model="selectedPayMethod">
          <el-radio label="微信支付" border>
            <i class="el-icon-success" style="color:#67C23A;"></i>
            微信支付
          </el-radio>
          <el-radio label="直接拿货" border>
            <i class="el-icon-success" style="color:#409EFF;"></i>
            直接拿货
          </el-radio>
        </el-radio-group>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="payDialogVisible1 = false">取 消</el-button>
        <el-button type="primary" @click="confirmPay">立即支付</el-button>
      </div>
    </el-dialog>


    <!-- 担保合作商支付对话框 -->
    <el-dialog
      title="选择支付方式"
      :visible.sync="payDialogVisible2"
      width="400px"
      @close="handlePayClose">
      <el-skeleton :loading="loading" animated>
        <template #template>
          <el-skeleton-item variant="text" style="width: 30%"/>
          <el-skeleton-item variant="text"/>
          <el-skeleton-item variant="text" style="width: 60%"/>
        </template>
        <template #default>
          <div class="goods-details">
            <h3>商品明细（共 {{ selectedOrderItems.length }} 项）</h3>
            <el-table :data="selectedOrderItems" border size="mini">
              <el-table-column prop="productName" label="商品名称" width="200"/>
              <el-table-column label="单价" width="120">
                <template #default="{row}">￥{{ (row.orderAmount / row.quantity).toFixed(2) }}</template>
              </el-table-column>
              <el-table-column prop="quantity" label="数量" width="100"/>
              <el-table-column label="小计" width="120">
                <template #default="{row}">
                  ￥{{ row.orderAmount.toFixed(2) }}
                </template>
              </el-table-column>
            </el-table>
            <div class="total-amount">
              订单总额：<span class="amount">￥{{ finalTotalAmount.toFixed(2) }}</span>
            </div>
          </div>
        </template>
      </el-skeleton>
      <div style="text-align:center;">
        <el-radio-group v-model="selectedPayMethod">
          <el-radio label="微信支付" border>
            <i class="el-icon-success" style="color:#67C23A;"></i>
            微信支付
          </el-radio>
          <el-radio label="银行转账" border>
            <i class="el-icon-success" style="color:#409EFF;"></i>
            银行转账
          </el-radio>
        </el-radio-group>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="payDialogVisible2 = false">取 消</el-button>
        <el-button type="primary" @click="confirmPay">立即支付</el-button>
      </div>
    </el-dialog>

    <!-- 新增地址弹窗 -->
    <el-dialog
      title="新增收货地址"
      :visible.sync="addAddressVisible"
      width="400px"
      append-to-body
    >
      <el-form :model="addressForm" ref="addressForm" :rules="addressRules" label-width="80px">
        <el-form-item label="地址标签" prop="userName">
          <el-input
            v-model="addressForm.userName"
            placeholder="请输入地址标签，如：家、公司、学校"
            maxlength="10"
            show-word-limit
          ></el-input>
        </el-form-item>
        <el-form-item label="收货地址" prop="address">
          <el-input v-model="addressForm.address" type="textarea" :rows="3" placeholder="请输入详细地址"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addAddressVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitAddress">确 定</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import {
  listPurchcar,
  getPurchcar,
  delPurchcar,
  addPurchcar,
  updatePurchcar,
  selectByproductId
} from "@/api/supply/purchcar";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import {Splitpanes, Pane} from "splitpanes";
import "splitpanes/dist/splitpanes.css";
import {createOrders} from "@/api/supply/psorders";
import {status} from "nprogress";
import {checkPermi, checkRole} from "@/utils/permission";
import {getUserProfile} from "@/api/system/user";
import { selectByUserId, addAddress } from "@/api/supply/address";

export default {
  name: "Purchcar",
  components: {Treeselect, Splitpanes, Pane},
  beforeRouteEnter(to, from, next) {
    next(vm => {
      // 在导航被确认时执行
      // 这个回调会在组件实例创建之后执行
      vm.$nextTick(() => {
        vm.getList();
        vm.getSupplier();
      });
    });
  },
  data() {
    return {

      //用户信息
      user: {},
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 所有部门树选项
      deptOptions: [],
      // 总条数
      total: 0,
      // 购物车表格数据
      purchcarList: [],
      purchcarList1: [],
      // 用于存储分组后的数据根据供应商Id
      groupedPurchcarList: {},

      // 用于存储所有 productId
      productIds: [],
      // 用于存储所有 quantity
      quantities: [],
      // 是否是普通用户
      isRetail: false,
      // 是否是战略合作商
      isStratagem: false,
      // 是否是担保合作商
      isGuarantor: false,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        productId: null,
        customerId: null,
        quantity: null
      },
      // 表单参数
      form: {},
      //供应商ID
      supplierId: null,

      defaultProps: {
        children: "children",
        label: "label"
      },
      // 表单校验
      rules: {},

      payMethods: [
        {value: '1', label: '微信支付'},
        {value: '2', label: '支付宝支付'},
      ],
      stratagemPayMethods: [
        {value: '1', label: '微信支付'},
        {value: '2', label: '直接拿货'},
      ],
      guarantorPayMethods: [
        {value: '1', label: '微信支付'},
        {value: '2', label: '银行转账'}
      ],
      selectedPayMethod: '1', // 默认选中微信支付
      confirmVisible: false,


      selectedOrdersCount: 0,

      //结算参数
      psOrderDto: [],
      // 用于控制下订单对话框的显示
      orderVisible: false,
      // 用于控制支付对话框的显示
      payDialogVisible: false,
      payDialogVisible1: false,
      payDialogVisible2: false,
      // 用于存储选中的商品信息
      selectedOrderItems: [],

      addressList: [],
      selectedAddressId: null,
      addAddressVisible: false,
      addressForm: {
        address: '',
        userId: '',
        userName: ''
      },
      addressRules: {
        userName: [
          { required: true, message: '请输入地址标签', trigger: 'blur' },
          { min: 1, max: 10, message: '长度在 1 到 10 个字符', trigger: 'blur' }
        ],
        address: [
          { required: true, message: '请输入收货地址', trigger: 'blur' }
        ]
      }
    };
  },
  watch: {
    // 根据名称筛选部门树
    supplierId(val) {
      this.$refs.tree.filter(val);
    }
  },
  //最终总价计算
  computed: {
    finalTotalAmount() {
      return this.purchcarList.filter(item => this.ids.includes(item.carId)).reduce((total, product) => {
        let price = product.unitPrice;
        // 应用批量优惠
        if (product.quantity >= 50) {
          price = price * 0.92;
        } else if (product.quantity >= 30) {
          price = price * 0.95;
        } else if (product.quantity >= 10) {
          price = price * 0.98;
        }
        return total + (price * product.quantity);
      }, 0);
    }
  },

  created() {
    this.getUser();
  },
  methods: {

    checkRole,
    checkPermi,
    getUser() {
      getUserProfile().then(response => {
        this.user = response.data;
        console.log('user:', this.user);
        console.log('roles', response.data.roles);

        response.data.roles.forEach(role => {
          if (role.roleKey === 'purchaser-retail' || role.roleKey === 'purchaser-Audited') {
            this.isRetail = true;
          } else if (role.roleKey === 'purchaser-guarantor') {
            this.isGuarantor = true;
          } else if (role.roleKey === 'purchaser-stratagem' || 'admin') {
            this.isStratagem = true;
          } else {
            //弹出提示
            this.$message({
              message: '您不是采购商，无法访问此页面',
              type: 'warning'
            });
          }

        });

        console.log('普通用户', this.isRetail);
      });
    },

    /** 查询购物车列表 */
    getList() {
      this.loading = true;
      listPurchcar(this.queryParams).then(response => {
        this.purchcarList1 = response.rows.map(item => {
          let price = item.unitPrice;
          // 应用批量优惠
          if (item.quantity >= 50) {
            price = price * 0.92;
          } else if (item.quantity >= 30) {
            price = price * 0.95;
          } else if (item.quantity >= 10) {
            price = price * 0.98;
          }
          return {
            ...item,
            totalAmount: price * item.quantity,
            stockQuantity: item.stockQuantity || 0 // 确保库存字段存在，默认为0
          };
        });
        console.log(this.purchcarList1);
        this.purchcarList = this.purchcarList1;
        this.groupPurchcarList();
        this.extractProductIdsAndQuantities();
        this.total = response.total;
        this.loading = false;
      });
    },

    /** 提取 productId 和 quantity */
    extractProductIdsAndQuantities() {
      this.productIds = this.purchcarList.map(item => item.productId);
      this.quantities = this.purchcarList.map(item => item.quantity);
      console.log('Product IDs:', this.productIds);
      console.log('Quantities:', this.quantities);
    },


    groupPurchcarList() {
      this.groupedPurchcarList = {};
      this.purchcarList.forEach(item => {
        if (!this.groupedPurchcarList[item.supplierId]) {
          this.groupedPurchcarList[item.supplierId] = [];
        }
        this.groupedPurchcarList[item.supplierId].push(item);
      });
      console.log(this.groupedPurchcarList);
    },


    /**查询供应商下拉树结构 */
    getSupplier() {
      listPurchcar(this.queryParams).then(response => {
        // 提取 supplierId 并转换为树形数据格式
        console.log(response.rows);

        this.deptOptions = this.transformData(response.rows);

      }).catch(error => {
        console.error("Failed to fetch supplier data:", error);
      });
    },
    transformData(rows) {
      // 创建供应商ID与名称的映射（使用Map保证唯一性）
      const supplierMap = new Map();

      // 遍历所有数据行，建立供应商ID与名称的对应关系
      rows.forEach(row => {
        if (!supplierMap.has(row.supplierId)) {
          supplierMap.set(row.supplierId, {
            id: row.supplierId,
            name: row.supplierName
          });
        }
      });

      // 转换为树形数据格式（显示名称+ID）
      return Array.from(supplierMap.values()).map(supplier => ({
        id: supplier.id,
        label: `${supplier.name} ID: ${supplier.id}`
      }));
    },
    filterNode(value, data) {
      // 实现过滤逻辑
      if (!value) return true;
      return data.id.indexOf(value) !== -1;
    },
    handleNodeClick(data) {
      // 处理节点点击事件
      this.purchcarList = this.purchcarList1.filter(item => item.supplierId === data.id);
      console.log(this.purchcarList);
    },


    handleReset() {
      // 重置操作
      this.$refs.purchcarTable.clearSelection()
      // 重置过滤后的数据
      this.purchcarList = this.purchcarList1
      // 清空选中ID数组
      this.ids = []
      console.log(this.purchcarList);
    },

    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        carId: null,
        productId: null,
        customerId: null,
        quantity: null,
        productName: '',
        stockQuantity: 0,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.carId)
      this.single = selection.length !== 1
      this.multiple = !selection.length

      // 调试
      console.log('实际选中ID:', [...this.ids]);
      console.log('当前总金额:', this.finalTotalAmount);

    },

    // 判断行是否可选择（库存为0时不可选）
    isSelectable(row) {
      return row.stockQuantity > 0;
    },

    /** 下订单按钮操作 */
    placeOrder() {
      // 校验选中项
      if (this.ids.length === 0) {
        this.$message.warning('请先选择要下单的商品');
        return;
      }

      // 构建订单数组
      this.selectedOrderItems = this.purchcarList
        .filter(item => this.ids.includes(item.carId))
        .map(item => ({
          supplierId: item.supplierId,
          customerId: item.customerId,
          orderAmount: item.totalAmount,
          paymentMethod: '微信支付', // 支付方式需要根据业务补充
          productId: item.productId,
          quantity: item.quantity,
          status: item.status,
          productName: item.productName,
          imageUrl: item.imageUrl,  // 添加imageUrl属性
          orderStatus: "0",
          stockQuantity: item.stockQuantity // 添加库存数量
        }));

      console.log('选中的商品信息：', this.selectedOrderItems); // 添加调试日志

      // 1. 状态校验逻辑
      const invalidProducts = this.selectedOrderItems.filter(order => order.status !== 1);
      if (invalidProducts.length > 0) {
        const errorList = invalidProducts
          .map(p => `"${p.productName}"（ID: ${p.productId}）`)
          .join('、');
        this.$message.error({
          dangerouslyUseHTMLString: true,
          message: `以下商品状态异常无法下单：<br>${errorList}`
        });
        return;
      }

      // 2. 库存校验逻辑
      const outOfStockProducts = this.selectedOrderItems.filter(order => order.stockQuantity < order.quantity);
      if (outOfStockProducts.length > 0) {
        const errorList = outOfStockProducts
          .map(p => `"${p.productName}"（库存: ${p.stockQuantity}, 需求: ${p.quantity}）`)
          .join('、');
        this.$message.error({
          dangerouslyUseHTMLString: true,
          message: `以下商品库存不足：<br>${errorList}`
        });
        return;
      }

      // 保存订单数量用于显示
      this.selectedOrdersCount = this.selectedOrderItems.length;
      // 显示对话框
      this.getAddressList(); // 获取地址列表
      this.orderVisible = true;
    },

    /** 仅下单按钮操作 */
    handleAbandonOrder() {
      if (!this.selectedAddressId) {
        this.$message.warning('请选择收货地址');
        return;
      }

      // 构建订单数据
      const supplierMap = new Map();
      this.selectedOrderItems.forEach(element => {
        const orderData = {
          supplierId: element.supplierId,
          customerId: element.customerId,
          orderAmount: element.orderAmount,
          paymentMethod: "未支付",
          products: [],
          quantities: [],
          orderStatus: "1", // 仅下单状态
          addressId: this.selectedAddressId
        };

        if (supplierMap.has(element.supplierId)) {
          supplierMap.get(element.supplierId).orderAmount += element.orderAmount;
          supplierMap.get(element.supplierId).products.push(element.productId);
          supplierMap.get(element.supplierId).quantities.push(element.quantity);
        } else {
          orderData.products.push(element.productId);
          orderData.quantities.push(element.quantity);
          supplierMap.set(element.supplierId, orderData);
        }
      });

      const orders = Array.from(supplierMap.values());

      // 调用创建订单接口
      createOrders(orders).then(response => {
        // 删除购物车项
        delPurchcar(this.ids).then(() => {
          // 更新购物车数据
          this.purchcarList1 = this.purchcarList1.filter(item => !this.ids.includes(item.carId));
          this.purchcarList = this.purchcarList.filter(item => !this.ids.includes(item.carId));
          this.ids = [];
          this.$refs.purchcarTable.clearSelection();
          this.getSupplier();

          this.$modal.msgSuccess("下单成功");
          this.orderVisible = false;

          // 跳转到个人订单页面
          this.$router.push({
            name: 'PersonOrders',
            query: { orderNumber: response.data }
          });
        }).catch(error => {
          console.error('购物车项删除失败', error);
          this.$message.error("购物车项删除失败: " + (error.msg || error.message));
        });
      }).catch(error => {
        this.$message.error('订单创建失败：' + (error.msg || error.message));
      });
    },

    /** 修改下单支付方法，使用新的createOrder接口 */
    handleConfirmOrder() {
      if (!this.selectedAddressId) {
        this.$message.warning('请选择收货地址');
        return;
      }

      // 构建订单数据
      const supplierMap = new Map();
      this.selectedOrderItems.forEach(element => {
        const orderData = {
          supplierId: element.supplierId,
          customerId: element.customerId,
          orderAmount: element.orderAmount,
          paymentMethod: null,
          products: [],
          quantities: [],
          orderStatus: "1", // 待支付状态
          addressId: this.selectedAddressId
        };

        if (supplierMap.has(element.supplierId)) {
          supplierMap.get(element.supplierId).orderAmount += element.orderAmount;
          supplierMap.get(element.supplierId).products.push(element.productId);
          supplierMap.get(element.supplierId).quantities.push(element.quantity);
        } else {
          orderData.products.push(element.productId);
          orderData.quantities.push(element.quantity);
          supplierMap.set(element.supplierId, orderData);
        }
      });

      const orders = Array.from(supplierMap.values());

      // 调用创建订单接口
      createOrders(orders).then(response => {
        // 关闭订单确认弹窗
        this.orderVisible = false;

        // 保存当前订单信息用于支付
        this.currentPayOrder = {
          orderNumber: response.data,
          originalOrders: orders,
          cartIds: this.ids
        };

        // 根据用户角色显示对应的支付弹窗
        if (this.isRetail) {
          this.payDialogVisible = true;
        } else if (this.isStratagem) {
          this.payDialogVisible1 = true;
        } else if (this.isGuarantor) {
          this.payDialogVisible2 = true;
        }

        this.$modal.msgSuccess("下单成功，请选择支付方式");
      }).catch(error => {
        this.$message.error('订单创建失败：' + (error.msg || error.message));
      });
    },

    /** 确认支付 */
    confirmPay() {
      if (!this.selectedPayMethod) {
        this.$message.warning('请选择支付方式')
        return
      }

      this.$confirm(`确认使用${this.selectedPayMethod}支付订单 ${this.currentPayOrder.orderNumber}？`, "支付确认", {
        confirmButtonText: "确认支付",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        // 调用支付接口
        const updateRequests = this.currentPayOrder.originalOrders.map(order => {
          return updatePsorders({
            ...order,
            orderStatus: "0",  // 已支付状态
            paymentMethod: this.selectedPayMethod
          });
        });

        // 批量执行更新
        Promise.all(updateRequests)
          .then(() => {
            // 支付成功后删除购物车项
            delPurchcar(this.currentPayOrder.cartIds).then(() => {
              // 更新购物车数据
              this.purchcarList1 = this.purchcarList1.filter(item => !this.currentPayOrder.cartIds.includes(item.carId));
              this.purchcarList = this.purchcarList.filter(item => !this.currentPayOrder.cartIds.includes(item.carId));
              this.ids = [];
              this.$refs.purchcarTable.clearSelection();
              this.getSupplier();

              this.$modal.msgSuccess("支付成功");
              // 关闭所有支付相关弹窗
              this.payDialogVisible = false;
              this.payDialogVisible1 = false;
              this.payDialogVisible2 = false;
              // 跳转到个人订单页面
              this.$router.push({ name: 'PersonOrders' });
            }).catch(error => {
              console.error('购物车项删除失败', error);
              this.$message.error("购物车项删除失败: " + (error.msg || error.message));
            });
          })
          .catch(error => {
            console.error('支付失败', error);
            this.$message.error("支付失败: " + (error.msg || error.message));
          });
      }).catch(() => {
        // 用户取消支付，不做任何操作
      });
    },

    /** 关闭支付弹窗 */
    handlePayClose() {
      this.selectedPayMethod = '1';
      this.currentPayOrder = null;
      this.payDialogVisible = false;
      this.payDialogVisible1 = false;
      this.payDialogVisible2 = false;
    },

    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const carId = row.carId || this.ids
      getPurchcar(carId).then(response => {
        // 确保form中包含所有需要的数据
        this.form = {
          ...response.data,
          productName: row.productName, // 确保产品名称存在
          stockQuantity: row.stockQuantity || 0, // 确保库存数量存在
          quantity: row.quantity // 确保数量与外部一致
        };
        this.open = true;
        this.title = "修改购物车";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 检查库存是否足够
          if (this.form.quantity > this.form.stockQuantity) {
            this.$message.warning(`商品库存不足，当前库存为 ${this.form.stockQuantity}`);
            return;
          }

          if (this.form.carId != null) {
            // 创建一个新对象，移除后端不需要的字段
            const submitData = { ...this.form };
            // 删除前端显示用的字段，避免后端实体类不匹配的错误
            delete submitData.productName;
            delete submitData.stockQuantity;

            updatePurchcar(submitData).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            }).catch(error => {
              this.$message.error("修改失败：" + (error.msg || error.message || '未知错误'));
            });
          } else {
            // 创建一个新对象，移除后端不需要的字段
            const submitData = { ...this.form };
            // 删除前端显示用的字段，避免后端实体类不匹配的错误
            delete submitData.productName;
            delete submitData.stockQuantity;

            addPurchcar(submitData).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            }).catch(error => {
              this.$message.error("新增失败：" + (error.msg || error.message || '未知错误'));
            });
          }
        }
      });
    },


    /** 导出按钮操作 */
    handleExport() {
      this.download('supply/purchcar/export', {
        ...this.queryParams
      }, `purchcar_${new Date().getTime()}.xlsx`)
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      const carIds = row.carId || this.ids;
      this.$modal.confirm('是否确认删除购物车编号为"' + carIds + '"的数据项？').then(function () {
        return delPurchcar(carIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },

    selectPersonOrders() {
      this.$router.push({name: 'PersonOrders'});
    },
    formatPrice(price) {
      return Number(price).toFixed(2)
    },

    /** 获取用户地址列表 */
    async getAddressList() {
      try {
        const response = await selectByUserId(this.user.userId);
        if (response.code === 200) {
          this.addressList = response.rows || [];
          if (this.addressList.length > 0 && !this.selectedAddressId) {
            this.selectedAddressId = this.addressList[0].id;
          }
        } else {
          this.$message.error(response.msg || '获取地址列表失败');
        }
      } catch (error) {
        this.$message.error('获取地址列表失败：' + error.message);
      }
    },

    /** 显示新增地址弹窗 */
    showAddAddressDialog() {
      this.addressForm = {
        address: '',
        userId: this.user.userId,
        userName: ''
      };
      this.addAddressVisible = true;
    },

    /** 提交新增地址 */
    submitAddress() {
      this.$refs.addressForm.validate(async (valid) => {
        if (valid) {
          try {
            const addressData = {
              ...this.addressForm,
              userId: this.user.userId
            };
            await addAddress(addressData);
            this.$message.success('添加地址成功');
            this.addAddressVisible = false;
            await this.getAddressList();
          } catch (error) {
            this.$message.error('添加地址失败：' + error.message);
          }
        }
      });
    },

    /** 表格行的类名 */
    tableRowClassName({row}) {
      if (row.stockQuantity <= 0) {
        return 'out-of-stock-row';
      }
      return '';
    },
  }


}
</script>

<style lang="scss" scoped>
.app-container {
  padding: 20px;

  .supplier-card {
    .supplier-header {
      display: flex;
      align-items: center;
      justify-content: space-between;
      margin-bottom: 20px;

      .title {
        font-size: 16px;
        font-weight: bold;
      }

      .search-input {
        width: 200px;
      }
    }

    .supplier-tree {
      ::v-deep .el-tree-node__content {
        height: 40px;

        &:hover {
          background-color: #f5f7fa;
        }
      }
    }
  }

  .cart-card {
    .cart-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 20px;

      .total-price {
        .label {
          font-size: 16px;
          color: #606266;
        }

        .amount {
          font-size: 24px;
          font-weight: bold;
          color: #f56c6c;
          margin-left: 10px;
        }
      }

      .action-buttons {
        .el-button {
          margin-left: 10px;
        }
      }
    }

    .cart-table {
      margin-bottom: 20px;

      .product-info {
        .product-name {
          font-size: 14px;
          font-weight: bold;
          margin-bottom: 5px;
        }

        .product-id {
          font-size: 12px;
          color: #909399;
        }

        &.out-of-stock {
          opacity: 0.6;
          color: #999;

          .product-name {
            text-decoration: line-through;
          }
        }
      }

      .price {
        color: #f56c6c;
        font-weight: bold;
      }

      .quantity {
        font-weight: bold;
        color: #409EFF;
      }

      .stock-quantity {
        font-weight: bold;
        color: #67C23A;

        &.stock-warning {
          color: #E6A23C;
        }

        &.stock-danger {
          color: #F56C6C;
        }
      }

      .total-amount {
        color: #f56c6c;
        font-weight: bold;
        font-size: 16px;
      }

      ::v-deep .el-table__row {
        transition: all 0.3s;

        &:hover {
          transform: translateY(-2px);
          box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
        }

        &.out-of-stock-row {
          background-color: #f5f5f5;
          color: #999;
        }
      }
    }
  }

  .pagination-container {
    text-align: right;
    padding-top: 20px;
  }
}

// 订单弹窗样式优化
.order-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  padding: 15px;
  border-radius: 8px;
  background-color: #f8f9fa;
  transition: all 0.3s;

  .item-left {
    display: flex;
    align-items: center;
    gap: 15px;

    .product-img {
      width: 80px;
      height: 80px;
      border-radius: 4px;
      overflow: hidden;

      ::v-deep .el-image__inner {
        width: 100%;
        height: 100%;
        object-fit: cover;
      }

      ::v-deep .image-slot {
        display: flex;
        justify-content: center;
        align-items: center;
        width: 100%;
        height: 100%;
        background: #f5f7fa;
        color: #909399;
        font-size: 20px;
      }
    }
  }

  .product-name {
    font-weight: bold;
    color: #303133;
  }

  .quantity {
    color: #409EFF;
    font-weight: bold;
  }
}

.total-amount {
  margin-top: 20px;
  padding: 15px;
  border-radius: 8px;
  background-color: #fff7ed;
  font-size: 18px;
  font-weight: bold;
  color: #f56c6c;
  text-align: right;
}

.address-section {
  margin: 20px 0;
  padding: 15px;
  background-color: #f8f9fa;
  border-radius: 8px;

  .section-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 15px;

    .title {
      font-size: 16px;
      font-weight: bold;
      color: #303133;
    }
  }

  .address-list {
    min-height: 120px;
    max-height: 300px;
    position: relative;

    .el-scrollbar {
      height: 250px;
    }

    ::v-deep .el-scrollbar__wrap {
      overflow-x: hidden;
      margin-bottom: 0 !important;
    }

    ::v-deep .el-scrollbar__view {
      padding: 0 5px;
    }

    .address-radio-group {
      display: flex;
      flex-direction: column;
      gap: 12px;
    }

    .address-radio-item {
      margin: 0;
      padding: 15px;
      border: 1px solid #dcdfe6;
      border-radius: 8px;
      transition: all 0.3s;
      cursor: pointer;
      width: 100%;
      box-sizing: border-box;

      &:hover {
        border-color: #409EFF;
        box-shadow: 0 2px 12px 0 rgba(0,0,0,.1);
      }

      &.is-selected {
        border-color: #409EFF;
        background-color: #ecf5ff;
      }

      .address-info {
        position: relative;
        padding-right: 20px;

        .address-tag {
          margin-bottom: 8px;

          .el-tag {
            font-size: 12px;
            padding: 0 8px;
            height: 24px;
            line-height: 24px;
          }
        }

        .address-main {
          font-size: 14px;
          color: #303133;
          margin-bottom: 8px;
          line-height: 1.4;
          word-break: break-all;
        }

        .address-time {
          font-size: 12px;
          color: #909399;
          display: flex;
          align-items: center;
          gap: 4px;

          .el-icon-time {
            font-size: 14px;
          }
        }
      }
    }
  }
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  padding: 10px 20px;
  gap: 12px;

  .el-button {
    padding: 10px 20px;
    font-size: 14px;
    border-radius: 4px;
    transition: all 0.3s;

    &:hover {
      transform: translateY(-1px);
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    }

    &[plain] {
      background: #fff;

      &:hover {
        background: #f5f7fa;
      }
    }

    i {
      margin-right: 5px;
      font-size: 16px;
    }
  }

  .el-button--primary {
    background: #409EFF;
    border-color: #409EFF;
    color: #fff;
    font-weight: 500;

    &:hover {
      background: #66b1ff;
      border-color: #66b1ff;
    }
  }

  .el-button--warning {
    &[plain] {
      color: #e6a23c;
      border-color: #e6a23c;

      &:hover {
        background: #fdf6ec;
        color: #d4963e;
        border-color: #d4963e;
      }
    }
  }
}

.order-dialog {
  ::v-deep .el-dialog__body {
    padding: 20px;
  }

  .order-content {
    .order-summary {
      margin-bottom: 24px;

      .summary-header {
        display: flex;
        align-items: center;
        margin-bottom: 16px;

        .title {
          font-size: 16px;
          font-weight: 600;
          color: #303133;
        }
      }
    }

    .order-list {
      max-height: 300px;
      overflow-y: auto;
    }

    .order-item {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 16px;
      margin-bottom: 12px;
      background: #f8f9fa;
      border-radius: 8px;
      transition: all 0.3s ease;

      &:hover {
        transform: translateY(-2px);
        box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
      }

      .item-left {
        display: flex;
        align-items: center;
        gap: 16px;

        .product-img {
          width: 80px;
          height: 80px;
          border-radius: 4px;
          overflow: hidden;
        }

        .product-info {
          .product-name {
            font-size: 14px;
            font-weight: 500;
            color: #303133;
            margin-bottom: 8px;
          }

          .product-price {
            font-size: 14px;
            color: #f56c6c;
          }
        }
      }

      .item-right {
        text-align: right;

        .quantity {
          font-size: 14px;
          color: #606266;
          margin-bottom: 4px;
        }

        .item-total {
          font-size: 16px;
          font-weight: 500;
          color: #f56c6c;
        }
      }
    }

    .address-section {
      background: #f8f9fa;
      border-radius: 8px;
      padding: 20px;
      margin-bottom: 24px;

      .section-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 16px;

        .title {
          font-size: 16px;
          font-weight: 600;
          color: #303133;
          display: flex;
          align-items: center;
          gap: 8px;

          i {
            color: #409EFF;
          }
        }
      }

      .address-radio-item {
        margin: 8px 0;
        padding: 16px;
        border: 1px solid #dcdfe6;
        border-radius: 8px;
        transition: all 0.3s ease;

        &.is-selected {
          border-color: #409EFF;
          background-color: #ecf5ff;
        }

        &:hover {
          border-color: #409EFF;
          transform: translateY(-2px);
          box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
        }

        .address-info {
          .address-tag {
            margin-bottom: 8px;
          }

          .address-main {
            font-size: 14px;
            color: #303133;
            margin-bottom: 8px;
            line-height: 1.4;
          }

          .address-time {
            font-size: 12px;
            color: #909399;
            display: flex;
            align-items: center;
            gap: 4px;
          }
        }
      }
    }

    .order-footer {
      .total-info {
        padding: 16px;
        background: #fff7ed;
        border-radius: 8px;

        .total-item {
          display: flex;
          justify-content: flex-end;
          align-items: center;
          margin-bottom: 8px;

          &:last-child {
            margin-bottom: 0;
          }

          &.highlight {
            .label {
              font-size: 16px;
              font-weight: 600;
            }

            .value {
              font-size: 24px;
              font-weight: 600;
            }
          }

          .label {
            color: #606266;
            margin-right: 8px;
          }

          .value {
            color: #303133;

            &.price {
              color: #f56c6c;
            }
          }
        }
      }
    }
  }

  .dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 12px;
    padding: 16px 20px;
    border-top: 1px solid #dcdfe6;

    .el-button {
      padding: 12px 20px;
      font-size: 14px;
      border-radius: 4px;
      transition: all 0.3s ease;

      &:hover {
        transform: translateY(-2px);
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
      }

      i {
        margin-right: 4px;
      }
    }
  }
}

// 购物车修改弹框样式
.product-name-display {
  font-size: 16px;
  font-weight: bold;
  color: #303133;
  padding: 5px 0;
}

.stock-display {
  display: flex;
  align-items: center;

  span {
    font-size: 16px;
    font-weight: bold;

    &.stock-normal {
      color: #67C23A;
    }

    &.stock-warning {
      color: #E6A23C;
    }

    &.stock-danger {
      color: #F56C6C;
    }
  }

  .stock-unit {
    font-size: 14px;
    color: #606266;
    margin-left: 4px;
    font-weight: normal;
  }

  .stock-status {
    margin-left: 10px;
  }
}

.quantity-tip {
  margin-left: 10px;
  color: #909399;
  font-size: 12px;
}
</style>
